<template>
  <el-dialog title="属性表" :visible.sync="visible" width="800px" top="5vh" append-to-body :before-close="beforeClose">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="属性名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入属性名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['prod:attribute:add']"
          >新增</el-button>
        </el-col>

      </el-row>

      <el-table v-loading="loading" :data="attributeList" height="260px">
        <el-table-column label="属性名称" align="center" prop="name" />
        <el-table-column label="属性值" align="center" >
          <template slot-scope="scope">

<!--            <el-tag size="mini" v-for="attributeValue in scope.row.attributeValueList" key="attributeValue.id">{{ attributeValue.value }}</el-tag>-->
            <span>{{ concat(scope.row.attributeValueList) }}</span>

          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['prod:attribute:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['prod:attribute:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改属性名对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="属性名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入属性名称" />
          </el-form-item>
          <el-divider content-position="center">属性值信息</el-divider>

          <el-tag
            :key="tag.value"
            v-for="tag in attributeValueList"
            closable
            :disable-transitions="false"
            @close="removeTag(tag)">
            {{ tag.value }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">添加</el-button>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

  </el-dialog>
</template>

<script>
import {addAttribute, delAttribute, getAttribute, listAttribute, updateAttribute} from "@/api/prod/attribute";

export default {
  data() {
    return {
      // 遮罩层
      visible: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 属性名表格数据
      attributeList: [],
      // 属性值表格数据
      attributeValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      categoryId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        needValueList: true,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "属性名称不能为空", trigger: "blur" },
          { max: 10, message: "属性名称不能超过10个字符", trigger: "blur" }
        ]
      },
      inputVisible: false,
      inputValue: ''
    };
  },
  methods: {
    // 显示弹框
    show(categoryId) {
      this.categoryId = categoryId;
      this.resetQuery()
    },

    getList() {
      this.loading = true;
      this.queryParams.categoryId = this.categoryId;
      listAttribute(this.queryParams).then(response => {
        this.attributeList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.visible = true;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.attributeValueList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加属性名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getAttribute(id).then(response => {
        this.form = response.data;
        this.attributeValueList = response.data.attributeValueList;
        this.open = true;
        this.title = "修改属性名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.categoryId = this.categoryId;
          this.form.attributeValueList = this.attributeValueList;
          if (this.form.id != null) {
            updateAttribute(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttribute(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除属性名编号为"' + ids + '"的数据项？').then(function() {
        return delAttribute(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    concat(attributeValueList){
      let attributeValueStr = "";

      for (let i = 0; i < attributeValueList.length; i++) {
        attributeValueStr += attributeValueList[i].value;
        if (i !== attributeValueList.length - 1){
           attributeValueStr += ", ";
        }
      }

      return attributeValueStr;
    },
    removeTag(tag) {
      this.attributeValueList.splice(this.attributeValueList.indexOf(tag), 1);
    },
    handleInputConfirm() {
      let inputValue = this.inputValue.trim();
      if (inputValue) {
        if(inputValue.length > 8){
          this.$modal.msgWarning("属性值长度不能超过8个字符!")
          return;
        }

        let existence = this.attributeValueList.some(item => item.value === inputValue);
        if(existence){
          this.$modal.msgWarning("该属性值["+ inputValue +"]已存在!")
          return;
        }
        this.attributeValueList.push({ value: inputValue });
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    beforeClose(){
      this.$emit('update')
      this.visible = false;
    }
  }
};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 10px;
}

.button-new-tag {
  margin-top: 10px;
  margin-left: 10px;
  height: 30px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-top: 10px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
